<template>
  <div id="patrolTaskEdit">
    <GoBack content="调拨信息" :backUrl="backUrl" />
    <div class="bodyContent">
      <!-- 三目运算判断 -->
      <vxe-toolbar perfect>
        <template #buttons>
          <el-form ref="taskFormRef" :model="taskForm" :rules="taskFormRule" label-width="140px" class="form-input-m" :inline-message="true">
            <el-row>
              <el-col :span="8">
                <el-form-item label="目标仓库" prop="tarStoreCode">
                  <VxePulldownSelectionWithNa
                    style="width: 100%"
                    :url="'/inv/storeManage/findStoreManageList'"
                    @confirmClick="SelectRowClick"
                    :tableColumn="[
                      { field: 'storeCode', title: '编码' },
                      { field: 'storeName', title: '名称' }
                    ]"
                    :aimKeys="[
                      { aimKey: 'tarStoreCode', rowKey: 'storeCode' },
                      { aimKey: 'tarStoreNa', rowKey: 'storeName' }
                    ]"
                    :displayTexts="['tarStoreNa']"
                    :displayTextObj="taskForm.tarStoreNa ? taskForm.tarStoreNa : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="来源仓库" prop="oriStoreCode">
                  <VxePulldownSelectionWithNa
                      style="width: 100%"
                      :url="'/inv/storeManage/findStoreManageList'"
                      @confirmClick="SelectRowClick"
                      :tableColumn="[
                      { field: 'storeCode', title: '编码' },
                      { field: 'storeName', title: '名称' }
                    ]"
                      :aimKeys="[
                      { aimKey: 'oriStoreCode', rowKey: 'storeCode' },
                      { aimKey: 'oriStoreNa', rowKey: 'storeName' }
                    ]"
                      :displayTexts="['oriStoreNa']"
                      :displayTextObj="taskForm.oriStoreNa ? taskForm.oriStoreNa : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入库人" prop="storagePersonnel">
                  <VxePulldownSelection
                    v-enterNextInput
                    :url="'/api/user/getUserInfoList'"
                    @confirmClick="dropPullDownConfirm"
                    :tableColumn="[
                      { field: 'username', title: '编号', width: '60px' },
                      { field: 'realname', title: '姓名' }
                    ]"
                    :aimKeys="[{ aimKey: 'storagePersonnel', rowKey: 'username' }]"
                    :displayTexts="['realname']"
                    :displayTextObj="taskForm.storagePersonnel ? taskForm.storagePersonnel : ''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="调拨时间">
                  <el-date-picker style="width: 200px" v-model="taskForm.documentDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="invoiceNumber" label="备注">
                  <el-input v-model="taskForm.invoiceNumber" type="text" placeholder="备注"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vxe-toolbar>

      <div class="contentDiv">
        <el-container>
          <el-aside width="100%">
            <el-divider content-position="left">
              商品信息
              <el-button size="small" type="success" class="add-btn" @click="showAddReagent">添加商品</el-button>
            </el-divider>
            <el-dialog title="选择商品" v-model="checkReagentShow" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false" width="1000px">
              <SelectReagentAllo ref="sltReagentRef"></SelectReagentAllo>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmReagent">确定</el-button>
                <el-button @click="closeReagentDialog">取消</el-button>
              </div>
            </el-dialog>
            <div style="height: calc(100% - 150px)">
              <vxe-table class="mb10" border ref="reagentTableRef" :data="taskForm.reagentList" :row-config="{ isCurrent: true, isHover: true, useKey: true, keyField: 'eqId' }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow height="auto">
                <vxe-column type="seq" width="30" title=""></vxe-column>
                <vxe-column field="oriStoreNa" title="来源仓库" align="center"></vxe-column>
                <vxe-column field="reaNo" title="商品编号" align="center"></vxe-column>
                <vxe-column field="reaNa" title="商品名称" align="center"></vxe-column>
                <vxe-column field="specModel" title="规格" align="center"></vxe-column>
                <vxe-column field="batchNum" title="批号" align="center"></vxe-column>
                <vxe-column field="expirDay" title="有效期" align="center"></vxe-column>
                <vxe-column field="amount" title="目标库存" align="center"></vxe-column>
                <vxe-column field="applyNum" title="申请数量" ref="tableForm3" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                  <template #default="{ row }">
                    <div>{{ row.applyNum }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.applyNum" placeholder="申请数量" @blur="pdNum(row)" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="unit" title="单位" align="center"></vxe-column>
                <vxe-column field="price" title="价格" align="center">
                  <template #default="{ row }">
                    <div>{{ row.costPrice }}</div>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.costPrice" placeholder="价格" @change="getCosts(row)" style="width: 100%"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="produceDate" title="生产日期" width="100"> </vxe-column>
                <vxe-column field="expiryDate" title="有效期" width="100"> </vxe-column>
              </vxe-table>
            </div>
            <div style="width: 100%; text-align: right; margin-top: 10px;">
              <el-button type="primary" v-loading="submiting" size="small" @click="saveForm('taskFormRef')">提交 </el-button>
              <el-button type="primary" v-loading="submiting" size="small" @click="goBack()">关闭 </el-button>
            </div>
          </el-aside>
        </el-container>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import GoBack from '@/components/GoBack.vue'; //返回组件
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import SelectReagentAllo from '@/components/SelectReagentAllo.vue';
import { formatDateTime, IsEmpty } from '@/utils/common';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';

import { notifyMessage, notifyType } from '@/utils/common';
import {funBdsJsResult} from "@/utils/Expression";

let { proxy }: any = getCurrentInstance();

let radio = ref(1);
let backUrl = ref('');
let userList: any = reactive([]);
let jygzzList: any = reactive([]);
let lzList: any = reactive([]);
let sltReagentRef = ref(null);
let reagentTableRef = ref(null);

let submiting = ref(false);
let checkReagentShow = ref(false);

let taskForm: any = reactive({
  id: '',
  planId: '',
  tarStoreCode: '',
  oriStoreCode: '',
  tarStoreNa: '',
  oriStoreNa: '',
  supplierCode: '',
  supplierName: '',
  storagePersonnel: '',
  documentDate: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  orderStatus:'5',
  invoiceDate: '',
  purOrderNumber: '',
  invoiceNumber: '',
  transferType: '',
  reagentList: []
});

let taskFormRule = {
  tarStoreCode: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  oriStoreCode: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  storagePersonnel: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  supplierCode: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ]
};
let reagentForm = reactive({
  orderInfoId: '',
  reaNo: '',
  reaNa: '',
  specModel: '',
  expirDay: '',
  proUnit: '',
  amount: '',
  costPrice: '',
  costs: 0,
  barcode: '',
  miniUnit: '',
  maxTemp: '',
  minTemp: '',
  stockCondition: '',
  batchNum:''
});

onMounted(() => {
  getJygzzList();
  getLzList();
  taskForm.id = proxy.$route.query.id ? proxy.$route.query.id.toString() : '';
  backUrl = proxy.$route.query.url.toString();
  taskForm.transferType = proxy.$route.query.transferType.toString();
  if (taskForm.id) {
    getPatrolTaskById();
  }
});
/**下拉选中行事件 */
async function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    taskForm[r.aimKey] = e.row[r.rowKey];
  });
  proxy.$nextTick(() => {
    taskForm.reagentList=[];
  })
}
//获取检测方式数据字典
function getJygzzList() {
  jygzzList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'JYGZZ' } })
    .then((res: any) => {
      Object.assign(jygzzList, res.data);
    })
    .catch((err: any) => {});
}
//获取流转集合
function getLzList() {
  lzList.length = 0;
  const url = '/inv/transfer/type/findInvTransferTypeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      Object.assign(lzList, res.data);
    })
    .catch((err: any) => {});
}

/**下拉选中 */
function dropPullDownConfirm(e) {
  e.aimKeys.forEach((m) => {
    taskForm[m.aimKey] = e.row[m.rowKey];
  });
}

//获取修改所有页面信息
function getPatrolTaskById() {
  const url = '/inv/orderInfo/findOrderInfoByAllot';
  proxy.$http
    .get(url, { params: { orderInfoId: taskForm.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        Object.assign(taskForm, res.data);
      }
    })
    .catch((err) => {
      proxy.$alert(err, '提示');
    });
}

function saveForm(formName: any) {  
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    submiting.value = true;
    let url = '';
    if (taskForm.id) {
      url = '/inv/orderInfo/editOrderInfo';
    } else {
      url = '/inv/orderInfo/addOrderInfo';
    }
    proxy.$http
      .post(url, taskForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('提交成功', VxeNotifyType.success);
          taskForm.id = res.data.id;
          //getPatrolTaskById();
          goBack();
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        submiting.value = false;
      })
      .catch((err) => {
        submiting.value = false;
      });
  });
}
function goBack(): void {
  if (backUrl) {
    proxy.$router.push(backUrl);
  } else {
    proxy.$router.go(-1); //返回上一层
  }
  proxy.$emit('closeDrawer');
}
function showAddReagent() {
  checkReagentShow.value = true;
  proxy.$nextTick(() => {
    sltReagentRef.value?.setPatrolTaskEqList(taskForm);
  })
}
function closeReagentDialog() {
  checkReagentShow.value = false;
}
function confirmReagent() {
  const sltEquipmentList = sltReagentRef.value.checkedRowList;
  const patrolTaskEqList = [];
  for (const item of sltEquipmentList) {
    const sm = taskForm.reagentList.some((p: any) => p.stockId === item.id);
    if (sm) {
      patrolTaskEqList.push(taskForm.reagentList.find((p: any) => p.stockId === item.id));
    } else {
      const patrolTaskEq = {
        id: '',
        stockId: item.id,
        orderInfoId: taskForm.id,
        oriStoreCode: item.storeCode,
        oriStoreNa: item.storeName,
        reaNo: item.reaNo,
        reaNa: item.reaNa,
        specModel: item.specModel,
        expirDay: item.expirDay,
        amount: item.quantity,
        proUnit: item.proUnit,
        batchNum: item.batchNum,
        costPrice: IsEmpty(item.price) ? 0 : item.price,
        produceDate: item.produceDate,
        expiryDate: item.expiryDate
      };
      patrolTaskEqList.push(patrolTaskEq);
    }
  }
  taskForm.reagentList = patrolTaskEqList;
  if (taskForm.reagentList && taskForm.reagentList.length > 0) {
    reagentTableRef.value.setCurrentRow(taskForm.reagentList[0]);
  }
  checkReagentShow.value = false;
}
function resetForm() {
      reagentForm.orderInfoId= taskForm.id;
      reagentForm.reaNo= '';
      reagentForm.reaNa= '';
      reagentForm.specModel= '';
      reagentForm.expirDay= '';
      reagentForm.proUnit= '';
      reagentForm.amount= '';
      reagentForm.costPrice= '';
      reagentForm.costs= 0;
      reagentForm.barcode= '';
      reagentForm.miniUnit= '';
      reagentForm.maxTemp= '';
      reagentForm.minTemp= '';
      reagentForm.batchNum= '';
}

function getCosts(row :any){
  row.costs=(row.applyNum) * (IsEmpty(row.price) ? 0 : row.costPrice);
}
// 判断申请是否大于库存数
function pdNum(row) {
  if (row.applyNum==0){
    VxeMessage('申请数量不能为0!', VxeNotifyType.error);
    row.applyNum=1;
  }
  if (row.applyNum>row.amount){
    VxeMessage('申请数量大于库存数量，请重新输入!', VxeNotifyType.error);
    row.applyNum=1;
  }
}
</script>
<style lang="scss" scoped>
#patrolTaskEdit {
  height: 100%;

  .bodyContent {
    height: calc(100% - 90px);

    .el-form {
      margin-top: 10px;
    }

    .contentDiv {
      background-color: $base-white;
      height: calc(100% - 95px);
      margin-top: 10px;

      .el-container {
        .mb10 {
          margin-bottom: 10px;
        }

        .add-btn {
          padding: 5px;
          margin-left: 10px;
        }

        .el-aside {
          background-color: $base-white !important;
          margin: 0;
          padding: 0 10px;
        }

        .el-main {
          background-color: $base-white;

          padding: 0 10px;

          .el-checkbox-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-checkbox {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-checkbox__label {
              padding-left: 5px;
            }
          }

          .el-radio-group .check-row-inline {
            height: 10px;
            line-height: 30px;
            padding: 0 5px 0 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            display: inline-block;

            .el-radio {
              width: 70px !important;
              margin-bottom: 2px;
            }

            .inst-checkboxClazz {
              width: auto !important;
              margin-bottom: 2px;
            }

            .el-radio__label {
              padding-left: 5px;
            }
          }
        }
      }

      .footerBtn {
        height: 32px;
        background-color: $base-white;
      }
    }
  }
}

:deep(.el-dialog) {
  padding: 0;

  .el-dialog__header {
    padding: 15px;
  }

  .el-dialog__body {
    padding: 0;

    .dialog-footer {
      margin: 10px;
      height: 32px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
